package com.northpool.operator.common.id;

import com.northpool.operator.annotation.InputParam;
import com.northpool.operator.annotation.InputParams;
import com.northpool.operator.annotation.OperatorInfo;
import com.northpool.operator.annotation.OutputParam;
import com.northpool.operator.annotation.OutputParams;
import com.northpool.operator.common.algorithm.OperatorTestBuild;
import com.northpool.operator.common.algorithm.TestParamBuilder;
import com.northpool.operator.param.ParamTool;
import com.northpool.operator.utils.StpOperatorHelper;

import java.security.SecureRandom;

@OperatorInfo(
        ref = "UUIDOperator",
        name = "UUID生成",
        description = "生成指定长度和间隔符的UUID")
@OutputParams({
        @OutputParam(ref = "uuid", name = "生成的UUID")
})
public class UUIDOperator extends StpOperatorHelper {

    @InputParams({
            @InputParam(ref = "length", name = "生成长度", desc = "随机生成的ID字符串长度 1-256之间", value = "32"),
            @InputParam(ref = "spitChar", name = "间隔符", desc = "ID中的间隔符", value = "-"),
            @InputParam(ref = "prefix", name = "前缀", desc = "填充到随机生成的ID之前", value = ""),
            @InputParam(ref = "suffix", name = "后缀", desc = "填充到随机生成的ID之后", value = ""),
    })
    public UUIDOperator() throws Exception {
    }

    public static void main(String[] args) throws Exception {
        OperatorTestBuild.execute(UUIDOperator.class, TestParamBuilder.aBuilder()
                .param("length", "16")
                .param("splitChar", "-")
                .param("prefix", "")
                .param("suffix", "")
                .build());
    }

    @Override
    public void execute(ParamTool paramTool) throws Exception {
        String spitChar = paramTool.getStr("spitChar");
        String lengthStr = paramTool.getStr("length");
        String prefix = paramTool.getStr("prefix");
        String suffix = paramTool.getStr("suffix");

        if (spitChar == null || spitChar.length() != 1) {
            throw new IllegalArgumentException("间隔符必须是一个字符");
        }

        int length = Integer.parseInt(lengthStr);
        if (length <= 0 || length > 256) {
            throw new IllegalArgumentException("生成长度必须在1到256之间");
        }

        // 生成UUID并处理
        SecureRandom random = new SecureRandom();
        StringBuilder uuidBuilder = new StringBuilder();
        for (int i = 0; i < length; i++) {
            int randomInt = random.nextInt(16); // 生成0到15之间的随机数
            uuidBuilder.append(Integer.toHexString(randomInt)); // 转换为十六进制字符
        }

        String uuidStr = uuidBuilder.toString();

        // 插入间隔符
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < uuidStr.length(); i++) {
            result.append(uuidStr.charAt(i));
            if ((i + 1) % 8 == 0 && i + 1 < uuidStr.length()) {
                result.append(spitChar);
            }
        }

        result("uuid", prefix + result + suffix);
    }
}